import axios from "axios";

// OSS uploadFile 必须
const options = {
  region: "oss-cn-shanghai.aliyuncs.com",
  accessKeyId: "xxx",
  accessKeySecret: "xxx",
  endpoint: "https://oss-cn-shanghai.aliyuncs.com",
  bucket: "xxxx"
};
const ossBaseUrl = "https://xxxx.oss-cn-shanghai.aliyuncs.com/";

// VOD fileChange 必须
const uploadAuthUrl = "http://xxxx/getVideoUploadAuth";
const vodBaseUrl =
  "https://xxxx.oss-cn-shanghai.aliyuncs.com/";
/**
 * 阿里云上传类
 * - 点播 fileChange
 ```
 回调：
 start(uploadFile) 开始上传
 progress(uploadInfo, totalSize, loadedPercent) 上传进度
 success(uploadInfo) 上传完成
 complete(uploadInfo) 全部上传完成
 error(error) 上传失败
 ```
 * - 其他 uploadFile
 */
class Upload {
  constructor() {
  }
  /**
   * STS 点播上传
   * @param {*} files
   * @param {*} maxSize 最大文件大小 默认10G
   */
  fileChange(files, maxSize = 1024 * 10) {
    if (!files[0]) {
      return false;
    }
    const _file = files[0];
    // 上传文件的size的单位为 字节(b)
    if (_file.size <= maxSize * 1024 * 1024) {
      this._getAuth()
        .then(() => {
          this._getUploder();
          // STS的上传方式，需要在userData里指定Title
          // https://help.aliyun.com/document_detail/55407.html?spm=a2c4g.11186623.2.48.1b0b6bd1eEYRew
          const info = {
            Title: _file.name,
            CateId: "1000017537",
            TemplateGroupId: "70898ad5cd246e59680ec8466c7a56ce"
          };
          const userData = JSON.stringify({ Vod: info });
          this._vod.addFile(_file, null, null, null, userData);
          this._vod.startUpload();
          console.log(`add file: ${_file.name}`);
          typeof this.start === "function" && this.start(_file);
        })
        .catch(error => {
          console.log(error);
          typeof this.error === "function" && this.error(error);
        });
    } else {
      typeof this.error === "function" &&
        this.error(`上传的文件大小超过${maxSize}M，请重新上传`);
    }
  }
  async _getAuth() {
    // 获取上传凭证
    return axios.post(uploadAuthUrl).then(res => {
      const data = res.data;
      if (data.code == 200) {
        this._securityToken = data.data.securityToken;
        this._accessKeyId = data.data.accessKeyId;
        this._accessKeySecret = data.data.accessKeySecret;
      } else {
        return Promise.reject(data.message);
      }
    });
  }
  /**
   * [JavaScript上传SDK](https://help.aliyun.com/document_detail/52204.html?spm=a2c4g.11186623.4.3.6ca4257eoLTS6D#%E4%B8%8A%E4%BC%A0%E5%9C%B0%E5%9D%80%E5%92%8C%E5%87%AD%E8%AF%81%E6%96%B9%E5%BC%8F(%E6%8E%A8%E8%8D%90%E4%BD%BF%E7%94%A8))
   */
  _getUploder() {
    /**
     * 获取上传文件列表
     * _vod.listFiles();
     * 清理上传文件列表
     * _vod.cleanList();
     * 开始上传
     * _vod.startUpload();
     * 停止上传
     * _vod.stopUpload();
     */
    this._vod = new AliyunUpload.Vod({
      // 文件上传失败
      onUploadFailed: (uploadInfo, code, message) => {
        console.log(
          `onUploadFailed: file:${
          uploadInfo.file.name
          },code:${code}, message:${message}`
        );
        typeof this.error === "function" &&
          this.error(uploadInfo, code, message);
      },
      // 文件上传完成
      onUploadSucceed: uploadInfo => {
        uploadInfo.url = `${vodBaseUrl}${uploadInfo.object}`;
        console.log(uploadInfo);
        typeof this.success === "function" && this.success(uploadInfo);
      },
      // 文件上传进度
      onUploadProgress: (uploadInfo, totalSize, loadedPercent) => {
        console.log(
          `onUploadProgress:file:${
          uploadInfo.file.name
          }, fileSize:${totalSize}, percent:${(loadedPercent * 100.0).toFixed(
            2
          )}%`
        );
        typeof this.progress === "function" &&
          this.progress(uploadInfo, totalSize, loadedPercent);
      },
      // 上传凭证超时
      onUploadTokenExpired: uploadInfo => {
        console.log("onUploadTokenExpired STS临时账号过期了");
        // 重新获取STS token，恢复上传
        this._vod.resumeUploadWithSTSToken(
          uploadInfo,
          this._accessKeyId,
          this._accessKeySecret,
          this._securityToken
        );
      },
      onUploadCanceled: uploadInfo => {
        console.log(`onUploadCanceled:file:${uploadInfo.file.name}`);
      },
      // 开始上传
      onUploadstarted: uploadInfo => {
        console.log(
          `onUploadStarted:${uploadInfo.file.name},endpoint:${
          uploadInfo.endpoint
          }, bucket:${uploadInfo.bucket}, object:${uploadInfo.object}`
        );
        this._vod.setSTSToken(
          uploadInfo,
          this._accessKeyId,
          this._accessKeySecret,
          this._securityToken
        );
      },
      onUploadEnd: uploadInfo => {
        console.log("onUploadEnd: uploaded all the files");
        typeof this.complete === "function" && this.complete(uploadInfo);
      }
    });
  }

  /**
   * 上传非视频文件
   * [更多信息](https://help.aliyun.com/document_detail/64047.html?spm=a2c4g.11186623.6.947.9dd1678atGgXcu)
   * @param {*} file input文件
   * @param {*} prefix 路径名前缀
   */
  uploadFile(file, prefix = "") {
    this._oss = new OSS.Wrapper(options);
    const detail = this._getFileDetail(file, prefix);
    return new Promise((resolve, reject) => {
      this._oss.multipartUpload(detail.key, file)
        .then(res => {
          console.log(res, detail);
          if (res.res.status === 200) {
            resolve(Object.assign(detail, { status: 200 }));
          } else {
            resolve(Object.assign(res, { status: 2000 }));
          }
        })
        .catch(err => resolve(Object.assign(err, { status: 2001 })));
    });
  }
  _getFileDetail(file, prefix = "") {
    let dot = file.name.lastIndexOf(".");
    // 文件名称 不含扩展名
    let realFileName = file.name.substring(0, dot);
    let fileExten = file.name.substring(dot, file.name.length);
    let timestamp = new Date().getTime();
    // 文件存储路径 路径文件可自定义
    let fileKey = `${prefix}${realFileName}_${timestamp}${fileExten}`;
    // oss存储位置、文件名
    let detail = {};
    detail.key = fileKey;
    // 进行中文url编码
    fileKey = encodeURI(fileKey);
    detail.url = ossBaseUrl + fileKey;
    return detail;
  }
  /**
   * @param {*} file input文件
   * @returns {*} 文件详情
   */
  uploadFileDetail(file) {
    let isIE = /msie/i.test(navigator.userAgent) && !window.opera;
    let pos = file.name.lastIndexOf(".");
    // 扩展名
    let fileExten = file.name.substring(pos + 1, file.name.length);
    let detail = {};
    detail.name = file.name;
    if (isIE) {
      let filePath = file.name;
      let fileSystem = new ActiveXObject("Scripting.FileSystemObject");
      let file = fileSystem.GetFile(filePath);
      detail.size = file.size;
    } else {
      detail.size = file.size;
    }
    detail.exten = fileExten;
    return detail;
  }
  /** 字节单位转换 */
  formatSize(bytes) {
    if (bytes === 0) return "0 B";
    let k = 1024;
    let sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
    let i = Math.floor(Math.log(bytes) / Math.log(k));
    return (bytes / Math.pow(k, i)).toFixed(2) + " " + sizes[i];
  }
  /**
   * @param {*} file input文件
   * @returns {string} 该文件的浏览器访问url
   */
  getObjectURL(file) {
    var url = null;
    if (window.createObjectURL != undefined) {
      // basic
      url = window.createObjectURL(file);
    } else if (window.URL != undefined) {
      // mozilla(firefox)
      url = window.URL.createObjectURL(file);
    } else if (window.webkitURL != undefined) {
      // webkit or chrome
      url = window.webkitURL.createObjectURL(file);
    }
    return url;
  }
}
export default new Upload();
